package serve

import (
	"encoding/json"
	"fmt"
	"net"
	"os"
	"os/exec"
	"strings"
)

// InnerConfig 存储心跳IP和配置文件
type InnerConfig struct {
	Config  Config
	InnerIp []net.IP
}

// Config 用于配置参数
type Config struct {
	LogLevel    string   `json:"logLevel"`
	ServePort   string   `json:"servePort"`
	TransPort   string   `json:"transPort"`
	LogFile     string   `json:"logFile"`
	WhiteIpList []string `json:"whiteIpList"`
}

// DefaultInnerConfig  is the default instance of *InnerConfig.
var DefaultInnerConfig = NewInnerConfig()

func NewInnerConfig() *InnerConfig {
	return &InnerConfig{Config: Config{}, InnerIp: make([]net.IP, 0)}
}

// LoadConfig 加载服务配置文件
func (IC *InnerConfig) LoadConfig(filename string) error {
	data, err := os.ReadFile(filename)
	if err != nil {
		return fmt.Errorf("error reading Config file: %v", err)
	}

	if err := json.Unmarshal(data, &IC.Config); err != nil {
		return fmt.Errorf("error parsing Config file: %v", err)
	}
	return nil
}

// NewInnerIp 存储心跳IP
func (IC *InnerConfig) NewInnerIp() error {
	cmd := exec.Command("bash", "-c", "ip a list | grep gui0 | awk '{print $2}' | awk -F '/' '{print $1}'")
	output, _ := cmd.CombinedOutput()

	// 按行分割并过滤空值
	lines := strings.Split(strings.TrimSpace(string(output)), "\n")

	for _, line := range lines {
		if line != "" {
			IC.InnerIp = append(IC.InnerIp, net.ParseIP(line))
		}
	}
	if len(IC.InnerIp) == 0 {
		return fmt.Errorf("error geting inner0:gui0 ip\n")
	}
	return nil
}
